<?php

namespace api\modules\v1\models\user;

use common\models\CacheKeys;
use common\models\Common;
use common\models\contract\ContractOrder;
use common\models\Functions;
use common\models\im\Im;
use common\models\prop\PropWarehouseChangeLog;
use common\models\Sign;
use common\models\Status;
use common\models\user\UserReal;
use common\models\user\UserUnusualLog;
use common\services\auth\AuthApiAliyun;
use common\services\umeng\UmengVerify;
use common\services\upload\AliyunOSS;
use Yii;
use yii\base\Exception;
use yii\db\Query;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class UserKyc extends UserReal
{

    /**
     * 验证规则
     */
    public function rules()
    {
        return [
            [['true_name', 'id_card'], 'required','message' => '{attribute}不能为空','on' => 'addEdit'],
            [['true_name','id_card'], 'filter', 'filter' => 'trim','on' => ['addEdit']],
        ];
    }

    /**
     * 设置属性名称
     * @return array
     */
    public function attributeLabels() {
        return [
            'true_name' => '姓名',
            'id_card' => '身份证号',
        ];
    }

    /**
     * 设置场景
     * @return array
     */
    public function scenarios() {
        $newScenarios =  [
            'addEdit' => [
                'true_name',
                'id_card',
            ],
        ];
        return array_merge(parent::scenarios(), $newScenarios);
    }

    public function doKyc() {
        $trans = Yii::$app->db->beginTransaction();
        try {
            if (!$this->validate()) {
                throw new Exception($this->getErrorSummary(true)[0]);
            }
//            (new Sign())->checkParams();
            $post = Yii::$app->request->post();

            $user = Yii::$app->getUser()->getIdentity()->toArray();
//            $terminal = strtolower(Yii::$app->request->headers->get('version-terminal',''));
//            if (empty($terminal)) {
//                throw new Exception('参数错误');
//            }

            CacheKeys::checkFrequency($user['id']);

            if ($user['is_kyc'] == Status::COMMON_RADIO_YES) {
                throw new Exception('您已经实名，无需重复实名');
            }
            # 姓名 身份证号
            $name = $post['true_name'];
            $idNo = $post['id_card'];
            $config = static::getCommonByKey(["block_id_card"]);
            if(!empty($config['block_id_card'])){
                $blockNames = explode(',',$config['block_id_card']);
            }else{
                $blockNames = [
                    '522427199707212530',
                    '131026199407072378',
                ];
            }
            // 黑名单
            if(in_array($idNo,$blockNames)){
                throw new Exception('黑名单用户,无法认证');
            }

            # 检查身份证信息是否被使用
            $idChk =(int) static::find()
                ->select('COUNT(*) as cou')
                ->leftJoin('jq_user u', 'u.id = jq_user_kyc.user_id')
                ->where(['!=', 'u.is_delete', 2])
                ->andWhere(['!=', 'u.status', 2])
                ->andWhere(['jq_user_kyc.id_card' => $idNo])
                ->count();
            if ($idChk >= 5) {
                throw new Exception('一个身份证最多只能认证5次');
            }

            // 相同身份下是否有被封禁的记录
            // SELECT * FROM jq_user_unusual_log WHERE type=5 and `status`=1 and user_id in (SELECT user_id FROM jq_user_kyc WHERE id_card = '422802200905142111' )
            $subQuery = (new Query())
                ->select('user_id')
                ->from('jq_user_kyc')
                ->where(['id_card' => $idNo]);

            // 检查子查询是否有结果
            $userIds = $subQuery->column();

            if (!empty($userIds)) {
                // 存在被封禁的记录
                $query = UserUnusualLog::find()
                    ->where(['type' => 5, 'status' => 1])
                    ->andWhere(['user_id' => $userIds]);

                $results = $query->count();
                if ($results > 0) {
                    // 同步封禁状态
                    UserUnusualLog::disableUser($user['id'], Status::USER_UNUSUAL_TYPE_CHAT, 999, '其他同名账号被封禁，自动作禁言处理');

                    $users = User::find()->where(['id' => $userIds])->asArray()->select('tx_code,id')->all();
                    foreach ($users as $u) {
                        $updateImUser['Tag_Profile_Custom_jinyan'] = (string) Status::COMMON_RADIO_YES;
                        $resIm = (new Im()) -> updateUser($u['tx_code'], $updateImUser);
                    }
                   
                }

                $query = UserUnusualLog::find()
                    ->where(['type' => 3, 'status' => 1])
                    ->andWhere(['user_id' => $userIds]);

                $results = $query->count();
                if ($results > 0) {
                    // 同步封禁状态
                    UserUnusualLog::disableUser($user['id'], Status::USER_UNUSUAL_TYPE_CIRCLE, 999, '其他同名账号被封禁，自动作禁言处理');
                }
            }

            

            $base64Data = trim($post['user_face']);
            if (empty($base64Data)) {
                throw new Exception('请更新APP，使用人脸识别');
            }
            $res = (new AuthApiAliyun())->idFaceIdentity($name, $idNo, $base64Data);

            if (empty($res) || $res['success'] == false || $res['code'] != 200) {
                throw new Exception($res['msg'] ?? "活体认证失败");
            }

            if ($res['data']['incorrect'] != 100) {
                throw new Exception('认证失败。');
            }

            # 活体
            if ($res['data']['score'] <= 0.4) {
                throw new Exception("认证失败，人证不一致");
            }

            $data = [];

            # 认证成功
            $data = array_merge($data, $this->getSaveData($this->scenario, Yii::$app->request->post()));

//            # 转到阿里云
//            $oss = new AliyunOSS();
//            $ossOBJ = $oss->getOBJ();
//            $path = "/tmp/";
//            $file = Functions::base64_image_content("data:image/png;base64," . $base64Data, $path);
//            $key = "kyc/" . md5(time() . rand(100, 999)) . ".png";
//            $ossOBJ->uploadFile($oss->_bucket, $key, $file);
//            #删除本地该图片
//            unlink($file);


            # put 方法传到阿里云
            $file = Functions::base64_image_content("data:image/png;base64," . $base64Data, '/tmp/');
            $key = (new AliyunOSS())->put('kyc',file_get_contents($file));
            #删除本地该图片
            unlink($file);


            $data['user_id'] = $user['id'];
            $data['id_card'] = $idNo;
            $data['true_name'] = $name;
            $data['user_face'] = $key;
            $data['oss_url'] = $key;
            $data['is_oss'] = Status::COMMON_RADIO_YES;
            $data['create_time'] = date("Y-m-d H:i:s");
            $data['status'] = Status::USER_KYC_STATUS_DONE;
            $res = static::insertData($data);
            if ($res === false) {
                throw new Exception('系统异常，请稍后重新提交！');
            }
            $this->afterKYC($user['id'], $user['parent_id']);
            $trans->commit();
            return Functions::formatRestAPI(0, '认证成功！');
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }


    /**
     * 获取
     * @return array
     */
    public function getInfo() {
        try {
            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $where['user_id'] = $user['id'];

            $result = [];
            $result['true_name'] = "";
            $result['id_card'] = "";
            $result['is_kyc'] = false;

            $info = static::getOneByWhere($where);
            if (empty($info)) {
                return Functions::formatRestAPI(0, '', $result);
            }

            $result['true_name'] = Functions::replaceStartFilter($info['true_name'], 0, mb_strlen($info['true_name']) - 1);
            $result['id_card'] = Functions::hiddenPhone($info['id_card'], 3, 15);
            $result['is_kyc'] = $user['is_kyc'] == Status::COMMON_RADIO_YES;


            return Functions::formatRestAPI(0, '', $result);
        } catch (Exception $e) {
            return Functions::formatRestAPI(1, $e->getMessage());
        }
    }

}
